<script setup lang='ts'>
import { useRoute,useRouter } from 'vue-router';
import bokInfo  from "@/store/bokInfo"
import commentStore from "@/store/commentStore"
import {onBeforeMount, onMounted, ref} from "vue"
import { ElMessage } from 'element-plus'
import articleApi  from "@/apis/articleApi"
import userStore from '@/store/userStore';
import queryIDStore from '@/store/queryIDStore'
import selfApi from '@/apis/selfApi';
import attentionStore from '@/store/attentionStore';

const route=useRoute()
const router=useRouter()
let b_id=queryIDStore()

//点击加载的时候就会判断，当前用户是否浏览过这个博客
onMounted(async()=>{
 
  console.log(route.query.id);
  if(route.query.id){
    b_id.queryBid=route.query.id
   
  }

// //获取当前被点击的博客和用户信息
await bokInfo().getCurrentPageByQuery( b_id.queryBid)


queryBok.value=bokInfo().queryBokList


  //浏览记录
  articleApi.storeViews(b_id.queryBid,userStore().info.id)
 
   //看当前用户是否关注这个博主
   const res=   (await selfApi.isAttention(userStore().info.id, queryBok.value.u_id)).msg
   
   if(res=="当前博客已关注"){
    attentionStore().isAttention=true
   }
   else{
    attentionStore().isAttention=false
   }

   //看当前用户是否收藏当前的博客
   const res1=(await selfApi.isCollection(userStore().info.id, queryBok.value?.b_id)).msg
   
   if(res1=="当前博客已收藏"){
    attentionStore().isCollection=true
   }
   else{
    attentionStore().isCollection=false
   }
})




// console.log(route.query.id);
const show=ref<boolean>(false)

const comments=ref()

const queryBok=ref()
//请求的query参数 id

 

// // //获取当前被点击的博客和用户信息
// await bokInfo().getCurrentPageByQuery( b_id.queryBid)


// queryBok.value=bokInfo().queryBokList



// console.log(queryBok.value);
//评论

//当前的博客的评论记录
const currentBokComments=ref()




 const commentValue=commentStore()

 //获取当前的博客记录
 currentBokComments.value= await commentValue.getComments( b_id.queryBid)

 const num =ref(0)



//提交评论
const commitComment=async(v:string)=>{
  num.value++
  //如果不为空
if(!checkVal(v)){
  if(commentValue.getCurrentTime()-commentValue.commitTime>5000){
  comments.value=null
  commentValue.getUserByComment()
  
 await commentValue.SetComments(b_id.queryBid,commentValue.userInfo?.id,v)
  currentBokComments.value=  commentValue.commentInfo
  // // //提交之后，清空编辑器的内容


  commentValue.setCommentTime(new Date().getTime())

  ElMessage({
    message: '保存成功',
    type: 'success',
  })
 
}
else{
  ElMessage({
    message: '发送评论太频繁,5s之后再试试',
    type: 'warning',
  })
  
}
}
else{
   //如果为空,show=true
   show.value=true
}
}


const  isCanDelete=()=>{
 return true
}


//点进去的点赞数和头像
  const goods= ref([])
 goods.value=   (await articleApi.getGoodsAndAvatar( b_id.queryBid)).data?.avatarList as []
 



 //是否有人点赞，按钮变换
 const isHaveGoods=()=>{
  if(queryBok.value?.goods!=0){
    return `感谢${queryBok.value?.goods}用户点赞`
  } 
  else{
    return "无用户点赞"
  }
 }



  const deleteComment =async(c_id:any,b_id:any)=>{
  await  commentValue.deleteComment(c_id,b_id);
    currentBokComments.value=  commentValue.commentInfo
  }

  //判断editor是否为空
  function checkVal(str:any)
	{
		let num = 0,
		reg = /<p>(&nbsp;|&nbsp;\s+)+<\/p>|<p>(<br>)+<\/p>/g;
		while (num < str.length && str != "")
		{
			num++;
			let k = str.match(reg);
			if (k) {
				str = str.replace(k[0], "");
			}
		}
		return str == "";
	}

  //当前用户是否关注这个博客的人
 let isAttention =ref()
//  console.log(queryBok.value);

//点击关注
//  currentId:当前用户的id   attentionId:被关注用户的id
 const attention=async(currentId:any,attentionId:any)=>{
          console.log("当前用户id: "+currentId+"被关注的用户id: "+attentionId);
       const res= (await  selfApi.clickAttention(currentId,attentionId)).msg
         ElMessage({
          type:res=="关注成功"?"success":"error",
          message:res
         })

        //  console.log(res);
         if(res=="关注成功"){
          attentionStore().isAttention=true
         }
         else{
          attentionStore().isAttention=false
         }
 }
 

//点击收藏
const collention=async(currentId:any,attentionId:any)=>{
         
       const res= (await  selfApi.clickCollection(currentId,attentionId)).msg
         ElMessage({
          type:res=="收藏成功"?"success":"error",
          message:res
         })

        //  console.log(res);
         if(res=="收藏成功"){
          attentionStore().isCollection=true
         }
         else{
          attentionStore().isCollection=false
         }
 }
</script>
<template>

 
   <!-- 文章点击之后的文章列表 -->
   <div class="border bg-white w-11/12 md:w-1/2 mb-10  md:mr-3 shadow-md rounded-md ">
         <!--头像，关注-->
      <div class="border-b">
        
         <section class="ml-3 p-3 flex ">
          <img :src="queryBok?.user?.avatar"   class=" w-[70px] h-[70px] object-cover rounded-full">
          <section class="grid grid-cols-1">
            <p class="text-sm ml-8 mt-2  font-semibold text-gray-600">{{queryBok?.user?.nickName}}</p>
            <el-button @click="attention(userStore().info.id,queryBok?.u_id)"
             class="!mt-1 !ml-3"  :type="attentionStore().isAttention?'danger':'success'"
              round>{{ attentionStore().isAttention?"已关注":"关注他"}}</el-button>
           
          </section>
         </section>
       </div>

       <!-- 文章的内容 -->
       <div class="border-b">
        <!--  文章的标题 -->
           <h1 class="ml-5 text-[20px]">{{queryBok?.title}}</h1>
            <!-- 发布时间 -->
            <p class=" ml-7 mt-3 text-sm">{{queryBok?.bok_create_time}}</p>
       </div>


        <!--  文章的内容 --> 
        <div class="border-b p-5 text-gray-600 font-normal leading-10">
             <section v-html="queryBok?.content">
             
             </section>
        </div>


        <div class="flex justify-center items-center">
        <!-- 关注这篇文章的用户有那些用户 -->
        <div class="flex justify-center itms-center truncate    " v-for="(avatar,index) in goods" :key="index">
          <img  v-if="goods" :src="avatar"  class=" mt-1 ml-1 w-12 h-12 object-cover rounded-full">

        </div>
      
      </div>

      <!-- 点赞数，和收藏 -->
      <div class="flex justify-center itms-center">
          <el-button  class="!m-6" type="danger" round>{{isHaveGoods()}}</el-button>
          
 
          <el-button class="!m-6" :type="attentionStore().isCollection?'success':'danger'"
            @click="collention(userStore().info.id,queryBok?.b_id)"
          round>{{ attentionStore().isCollection?"已收藏":"收藏帖子"}}</el-button>
        </div> 


          <!-- 发表评论区，提交后在显示评论(后续循环每个文章的评论,根据博客的b_id)-->
       
        
      <div v-for="(v,index) in currentBokComments" :key="index"
       class="border m-3 rounded-md" v-if="currentBokComments">
        
         <section class="ml-3 p-3 flex ">
          <img :src="v.user?.avatar"   class="  w-9 h-9 object-cover rounded-full">
           <p class="text-sm ml-3 leading-9">{{v.user?.nickName}}&nbsp;更新于&nbsp;{{v.createCommentTime}}</p>
         </section>


    <div class="flex-col">
      <section class= "bg-gray-300 rounded-md p-2 ml-3" v-html="v.content">
        </section>
        <!-- 删除评论，作者和发表评论的人都可以删除 -->
     <div class="flex justify-end mr-3 p-1">
      <section v-if="isCanDelete()" >
         <el-button size="small" type="danger" v-if="v.user.id==userStore().info?.id"
         @click="deleteComment(v.c_id, b_id.queryBid)" round>删除</el-button>
       </section>
     </div>
    </div>
      
       </div> 
    
     <div>
      <div class="border-t bg-gray-300 p-3">
        <h1 class="">发表评论</h1>
      </div>
                           
      <WangEditorEditor  v-model="comments"  :key="num" />
      <p class="bg-red-400 rounded-md w-1/2 mt-3 mb-1 text-sm" :class="{'animate-pulse':show}"
       v-if="show">&nbsp;发表的内容不能为空</p>

      <div>
        <el-button class="!m-6" type="primary" @click="commitComment(comments)" round>保存提交</el-button>
      </div> 
    </div>
  
    </div> 
 
 
</template>
<style scoped lang='scss'>


</style>